/**
 * 存放在public/audio目录下的音频文件
 */
const audios = {
  alert: 'error001.mp3',
  success: 'success001.mp3',
  warning: 'error001.mp3',
  error: 'error002.mp3',
  jiu: 'jiu001.mp3',
  keyDown: 'keydown.mp3',
  correct: 'correct.mp3'
}
const gifs = {
  firework: 'firework.gif',
  happy: 'happy.gif'
}
/**
 * 这个类主要实现键盘对音频的控制
 * 不同的案件可以播放不同的声音
 */
class keyboardAudio {
  registeredKeys = {}
  defaultAudios = {}
  constructor() {
    this.audio = null
    Object.keys(audios).forEach((key) => {
      this.defaultAudios[key] = new Audio('/assets/audio/' + audios[key])
    })
  }
  play(type) {
    if (typeof type === 'function') {
      type()
      return
    }
    this.defaultAudios[type].play()
  }
  //注册指定的按键到对应的音频
  register(key, audio) {
    // 如果registeredKeys已经注册过key，则报错
    if (this.registeredKeys[key]) {
      throw new Error(`Key ${key} is already registered.`)
    }
    // 创建一个Audio对象
    if (typeof audio === 'function') {
      this.registeredKeys[key] = audio
    } else if (audio.indexOf('mp3') === -1) {
      const audioPath = '/assets/audio/' + audios[audio]
      this.audio = new Audio(audioPath)
    } else {
      this.audio = new Audio(audio)
    }
    this.registeredKeys[key] = (e) => {
      // 如果按下的按键是指定的按键
      if (e.key === key) {
        if (typeof audio === 'function') {
          audio()
          return
        }
        // 播放音频
        this.audio.play()
      }
      // 如果key为任意键，则播放音频
      if (key === 'keyDown') {
        if (this.registeredKeys[e.key]) return
        this.audio.play()
      }
    }
    // 监听按键按下事件
    document.addEventListener('keydown', this.registeredKeys[key])
  }
  unregister(key) {
    // 停止播放音频
    this.audio?.pause()
    //取消监听
    document.removeEventListener('keydown', this.registeredKeys[key])
  }
  destroy() {
    // 停止播放音频
    this.audio?.pause()
    // 取消所有按键监听
    Object.keys(this.registeredKeys).forEach((key) => {
      document.removeEventListener('keydown', this.registeredKeys[key])
      delete this.registeredKeys[key]
    })
  }
}
export const KeyboardAudioCls = keyboardAudio
const KeyboardAudio = new keyboardAudio()
export default KeyboardAudio
